package pro.lingwu.station.controller;

import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pro.lingwu.station.dto.db.User;
import pro.lingwu.station.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;


/**
 * 用户信息的控制器，
 * 包括注册、登录、更新
 * @author @lingwu
 * @date created in 2021/11/16
 */
@Api(tags = "user")
@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @ApiOperation(value = "用户注册", response = ResponseEntity.class)
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = User.class),
    })
    @PostMapping("/user")
    public ResponseEntity<?> regUser(@Valid User user,
                                     @RequestBody(required = false) MultipartFile photo) throws IOException {
        // 交给服务层
        userService.addUser(user, photo);
        // 返回结果
        return ResponseEntity.ok(user);
    }

    @ApiOperation(value = "用户登录")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = User.class),
            @ApiResponse(code = 404, message = "not found")
    })
    @GetMapping("/user/{account}")
    public ResponseEntity<?> userSignIn(@PathVariable String account,
                                        String password, HttpServletRequest request){
        // 数据交给服务层
        User user = userService.signIn(request, account, password);
        // 返回结果
        if (user == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(user);
    }

    @ApiOperation(value = "更新用户信息")
    @PutMapping("/user/{account}")
    public ResponseEntity<?> updateUser(@PathVariable String account,
                                        @RequestParam(name = "password", required = false) String password,
                                        @RequestParam(name = "nickname", required = false) String nickname,
                                        @RequestParam(name = "phone", required = false) String phone,
                                        @RequestParam(name = "email", required = false) String email,
                                        MultipartFile photo) throws IOException {
        // 封装数据到对象中
        User user = new User(account, password, null, nickname, phone, email);
        // 交给服务层
        userService.updateUser(user, photo);
        // 返回结果
        return ResponseEntity.ok(account);
    }

}
